<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>


    <!--卡片视图区域-->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>
        </el-col>
      </el-row>


      <!--表格-->
      <el-table
          :data="cateList"
          style="width: 100%;margin-bottom: 20px;"
          row-key="catId"
          border
          :tree-props="{children: 'children'}">

        <!--index-->
        <el-table-column type="index" label="#">
          <template slot-scope="scope">
            {{ scope.row.index }}
          </template>
        </el-table-column>

        <!--商品分类列-->
        <el-table-column
            prop="catName"
            label="分类名称">
        </el-table-column>

        <!--是否有效列-->
        <el-table-column
            prop="catDeleted"
            label="是否有效">
          <template slot-scope="scope">
            <i class="el-icon-success " v-if="scope.row.catDeleted===0" style="color: green;font-size: 20px"></i>
            <i class="el-icon-error" v-else style="color: red"></i>
          </template>
        </el-table-column>

        <!--排序列-->
        <el-table-column
            prop="catLevel"
            label="排序">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.catLevel===0">一级</el-tag>
            <el-tag type="success" v-else-if="scope.row.catLevel===1">二级</el-tag>
            <el-tag type="warning" v-else-if="scope.row.catLevel===2">三级</el-tag>
          </template>
        </el-table-column>

        <!--操作列-->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 编辑按钮-->
            <el-button type="primary"
                       icon="el-icon-edit"
                       @click="showEditCateDialog(scope.row)"
                       size="mini">编辑
            </el-button>
            <!-- 删除按钮-->
            <el-button type="danger"
                       icon="el-icon-delete"
                       @click="deleteCateById(scope.row)"
                       size="mini">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[5,10,15,20]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>

      <!--  添加分类的对话框-->
      <el-dialog
          title="添加分类"
          :visible.sync="addCateDialogVisible"
          width="50%"
          @close="addCateDialogClosed"
          :close-on-click-modal="false ">

        <!-- 内容主体区域-->
        <!--添加分类的表单-->
        <el-form :model="addCateForm"
                 :rules="addCateFormRules"
                 ref="addCateFormRef" label-width="90px">
          <el-form-item label="分类名称:" prop="cat_name">
            <el-input v-model="addCateForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类">
            <!--options用于指定数据源-->
            <!--props用来指定配置对象-->
            <el-cascader
                v-model="selectedKeys"
                :options="parentCateList"
                :props="cascaderOptions"
                @change="parentCateChanged"
                clearable
            ></el-cascader>
          </el-form-item>
        </el-form>

        <!-- 底部区域-->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addCateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
      </el-dialog>
    </el-card>


    <!-- 编辑分类的对话框-->
    <el-dialog
        title="编辑分类"
        :visible.sync="editCateDialogVisible"
        width="50%"
        @close="editCateDialogClosed"
        :close-on-click-modal="false ">

      <!-- 内容主体区域-->
      <el-form :model="editCateForm"
               :rules="editCateFormRules"
               ref="editCateFormRef" label-width="90px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域-->
      <span slot="footer" class="dialog-footer">
          <el-button @click="editCateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "Cate",
  data() {
    return {
      //商品分类的数据列表
      cateList: [],

      //查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      //总数据条数
      total: 0,
      //为table指定列的定义
      columns: [{
        label: "分类名称",
        prop: "catName"
      }
      ],
      //展示添加分类对话框
      addCateDialogVisible: false,
      //添加分类的表单对象
      addCateForm: {
        //将要添加的分类的名称
        cat_name: '',
        cat_pid: 0,
        //分类的等级，默认要添加的是一级分类
        cat_level: 0,

      },

      //添加分类表单的验证规则
      addCateFormRules: {
        cat_name: [
          {required: true, message: "请输入分类名称", trigger: 'blur'}
        ]
      },
      //父级分类的列表
      parentCateList: [],
      //指定级联选择器的配置对象
      cascaderOptions: {
        value: 'catId',
        label: 'catName',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: true
      },
      //选中的父级分类的Id数组
      selectedKeys: [],

      //编辑分类表单
      editCateForm: {
        cat_name: '',
        cat_id: 0,
      },
      editCateDialogVisible: false,

      editCateFormRules: {
        cat_name: [
          {required: true, message: "请输入分类名称", trigger: 'blur'}
        ]
      },

    }
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const {data: res} = await this.$http.get("categories", {params: this.queryInfo});
      if (res.status !== 200) {
        return this.$message.error("获取商品分类列表失败");
      }
      console.log(res);
      this.cateList = res.data;
      this.total = res.total;

      //为数据源设置索引
      for (let i = 1; i <= this.cateList.length; i++) {
        this.cateList[i - 1].index = this.queryInfo.pagesize * (this.queryInfo.pagenum - 1) + i
      }
    },
    //监听pagesize改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getCateList();
      this.queryInfo.pagenum = 1;
    },
    //监听pagenum改变
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getCateList();
    },
    //监听添加分类对话框关闭事件
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields();
      this.selectedKeys = [];
      this.addCateForm.cat_level = 0;
      this.addCateForm.cat_pid = 0;
      this.addCateForm.cat_name = '';
    },
    //点击按钮展示添加分类的对话框
    showAddCateDialog() {
      this.getParentCateList();
      this.addCateDialogVisible = true;
    },
    //获取父级分类的数据列表
    async getParentCateList() {
      const {data: res} = await this.$http.get("/categories", {
        params: {
          type: 2
        }
      })
      if (res.status !== 200) {
        return this.$message.error("获取父级分类数据失败")
      }
      this.parentCateList = res.data
      console.log(this.parentCateList);
    },
    //选择项发生变化触发这个函数
    parentCateChanged() {
      console.log(this.selectedKeys);
      if (this.selectedKeys.length > 0) {
        this.addCateForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1];
      }
      this.addCateForm.cat_level = this.selectedKeys.length;
    },
    //点击按钮添加分类
    addCate() {
      console.log(this.addCateForm);
      this.$refs.addCateFormRef.validate(async validate => {
        if (!validate) return;
        const {data: res} = await this.$http.post("categories", this.addCateForm)
        console.log(res);
        if (res.status !== 201) {
          return this.$message.error("添加分类失败");
        }

        this.$message.success("添加分类成功");
        await this.getCateList();
        this.addCateDialogVisible = false;
      })

    },
    async deleteCateById(category) {
      console.log(category);
      const resultConfirm = await this.$confirm("该操作将永远删除分类，是否继续", "提示", {
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(err => err)
      if (resultConfirm !== "confirm") {
        return this.$message.info("已取消删除操作");
      }
      const {data: res} = await this.$http.delete(`categories/${category.catId}`)
      if (res.status !== 200) {
        this.$message.error("删除失败");
      }
      this.$message.success("删除成功");
      await this.getCateList();
    },
    //监听编辑分类表单关闭事件
    editCateDialogClosed() {
      this.$refs.editCateFormRef.resetFields();
    },
    //展示编辑分类对话框
    showEditCateDialog(category) {
      this.editCateDialogVisible = true;
      this.editCateForm.cat_name = category.catName;
      this.editCateForm.cat_id = category.catId;
    },

    //编辑处理事件
    editCate() {
      this.$refs.editCateFormRef.validate(async validate => {
        if (!validate) {
          console.log("验证不通过");
          return;
        }
        const {data: res} = await this.$http.put(`/categories/${this.editCateForm.cat_id}`, {
          cat_name: this.editCateForm.cat_name
        })
        console.log(res);
        this.editCateForm.cat_name = '';
        this.editCateForm.cat_id = 0;
        await this.getCateList()
        this.editCateDialogVisible = false;
      })
    },
  },
}
</script>

<style scoped lang="less">

</style>